<template>

  <basic-container>
    <div v-if="showIndex === 1">
      <avue-crud
          :key="reload"
          ref="commonCrud"
          v-if="loadFlag"
          :table-loading="loading"
          v-bind="bindVal"
          v-on="onEvent"
          v-model:page="page"
          v-model="form"
      >
        <!--  右侧按钮 -->
        <template v-if="buttonList.menuList" #menu="{row}">
          <template v-for="item in buttonList.menuList">
            <!--路由跳转 -->
            <el-button
                v-if="item.mode == 'router' && (item.info.show ? row[item.info.prop] == item.info.show : true) && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'"
                @click="routerFn(row,item)"
                :icon="item.icon" text>{{ item.name }}
            </el-button>

            <!--切换 -->
            <el-button
                v-if="item.mode == 'switch' && (row[item.info.prop] == item.info.show || row[item.info.prop] == item.info.show1)  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'" @click="switchFn(row,item)" :icon="item.icon" text>{{ item.name }}
            </el-button>

            <!-- 组件打开-->

            <el-button
                v-if="item.mode == 'commd'  && (item.info.show ? row[item.info.prop] == item.info.show : true)  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'"
                @click="commdFn(row,item)"
                :icon="item.icon" text>{{ item.name }}
            </el-button>

            <!--弹框打开 -->
            <el-button
                v-if="item.mode == 'dialog' && (item.info.show ? row[item.info.prop] == item.info.show : true)  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'"
                @click="dialogFn(row,item)"
                :icon="item.icon" text>{{ item.name }}
            </el-button>

            <!-- 打开一个外部页面-->
            <el-button
                v-if="item.mode == 'openurl'  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'" @click="openUrl(row,item)"
                :icon="item.icon"
                text>{{ item.name }}
            </el-button>
          </template>
        </template>

        <!--上方按钮-->
        <template #menu-left>


          <template v-for="item in buttonList.menuLeftList" v-if="buttonList">
            <!--路由跳转 -->
            <el-button
                v-if="item.mode == 'router'  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'success'" plain
                @click="routerFn(null,item)"
                :icon="item.icon">{{ item.name }}
            </el-button>


            <!-- 组件打开-->

            <el-button
                v-if="item.mode == 'commd'  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'" plain
                @click="commdFn(null,item)"
                :icon="item.icon">{{ item.name }}
            </el-button>

            <!--弹框打开 -->
            <el-button
                v-if="item.mode == 'dialog'  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'" plain
                @click="dialogFn(null,item)"
                :icon="item.icon">{{ item.name }}
            </el-button>

            <!-- 打开一个外部页面-->
            <el-button
                v-if="item.mode == 'openurl'  && ((this.option.permissionOption.enable && item.permission)?this.permissions.includes(item.permission):true)"
                :type="item.type?item.type:'primary'" @click="openUrl(null,item)"
                :icon="item.icon" plain
            >{{ item.name }}
            </el-button>
          </template>


        </template>

      </avue-crud>


    </div>
    <!-- 动态组件-->

    <div v-if="showIndex === 2">
      <div>
        <div class="header">
        <span>
          <div class="header_div" @click="showIndex = 1">
            <el-icon><Back/></el-icon>
            <span>{{ comTitle ? comTitle : '返回' }}</span>
          </div>
        </span>
        </div>
        <div class="btm"></div>
      </div>
      <component :is="bottomPanel" ref="comRef" @close="close" @refreshData="refreshData"
                 @comClose="comClose"></component>
    </div>


    <!-- 弹框-->
    <div v-if="dialogVisible">
      <el-dialog :title="comTitle?comTitle:'返回'" v-model="dialogVisible" @close="dialogVisible = false"
                 :width="dialogWidth?dialogWidth:'60%'">
        <component :is="bottomPanel" ref="comRef" @close="close" @refreshData="refreshData"
                   @updateDialogVisible="updateDialogVisible"></component>
      </el-dialog>


    </div>


  </basic-container>
</template>

<script>

// import {httpRequest} from '@/src/crud/api/crudApi'

import {httpRequest} from "../../crud/api/crudApi";

export default window.$simpleCrudCommon({
      props: {

        // 表字段
        crudOptionProps: {
          default: {
            buttonList: {}
          },
          type: Object
        }

      },

      data() {
        return {
          // 1: 列表, 2: 组件
          showIndex: 1,
          reload: Math.random(),
          loadFlag: false,
          crudOption: {},
          // 组件标题
          comTitle: "",
          //  是否开启弹框

          dialogVisible: false,
          // 弹框宽度
          dialogWidth: '',
          // 权限列表
          permissions: [],
          enablePermissions: false,
          buttonList: {
            menuList: [],
            menuLeftList: [],
            headerList: []
          },
          // 动态组件
          bottomPanel: null,
          operate: false,


        };
      },

      created() {

       Object.assign( this.crudOption,this.crudOptionProps)
        console.log("1111")

        this.loadFlag = true;
        this.loading = false;
        this.reload = Math.random()
        this.menuList();

      },
      methods: {
        // 列表之前
        listBefore(params, form) {
          this.$emit("listBefore", params, form);
        },
        // 列表之后
        listAfter(data) {
          this.$emit("listAfter", data);
        },
        // 新增之前
        addBefore(form) {
          this.$emit("addBefore", form);
        },
        // 新增之后
        addAfter(data) {
          this.$emit("addAfter", data);
        },
        // 修改之前
        updateBefore(form) {
          this.$emit("updateBefore", form);
        },
        // 修改之后
        updateAfter(data) {
          this.$emit("updateAfter", data);
        },
        // 删除之前
        delBefore(row, index) {
          this.$emit("delBefore", row, index);
        },
        // 删除之后
        delAfter(data, row, index) {
          this.$emit("delAfter", data, row, index);
        },

        // 菜单列表

        menuList() {

          console.log(this.crudOptionProps)
          if (this.crudOptionProps.buttonList) {
            this.buttonList.menuList = []
            this.buttonList.headerList = []
            this.buttonList.menuLeftList = []
            this.crudOptionProps.buttonList.forEach(item => {
              switch (item.menuType) {
                case  'menu':
                  this.buttonList.menuList.push(item)
                  break;
                case  'header':
                  this.buttonList.headerList.push(item)
                  break;
                case 'menuLeft':
                  this.buttonList.menuLeftList.push(item)
                  break;
                default:
                  return
              }
            })


          }
          console.log(this.buttonList)
        },
        // 路由
        routerFn(row, item) {


          let url = item.info.url
          let prop = item.info.prop
          if (url) {
            if (url) {
              if (prop && item.info.value) {
                this.$router.push({path: url, params: {[prop]: item.info.value}})
              } else {
                this.$router.push(url)
              }
            }
          }
        },
        // 状态切换
        switchFn(row, item) {
          let url = item.info.url;
          let prop = item.info.prop;
          let param = item.info.param;
          let confirmMsg = item.info.confirmMsg;
          if (undefined == confirmMsg) {
            confirmMsg = "是否要操作此条数据";
          }
          if (row) {
            // 遍历param的参数
            for (let key in param) {
              let value = param[key]
              if (null != value && value.toString().startsWith("$")) {
                value = value.replace("$", "")
                param[key] = row[value]
              }
            }
          }

          if (url) {

            this.$confirm(confirmMsg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              httpRequest(url, param, item.info.postType).then(res => {
                if (res.status == 200) {
                  if (item.info.successMsg) {
                    this.$message.success(item.info.successMsg)
                  }
                  this.getList()
                } else {
                  if (item.info.errorMsg) {
                    this.$message.error(item.info.errorMsg)
                  } else {
                    this.$message.error(res.msg)
                  }
                }
              });
            })
          }
        },
        // 组件打开
        commdFn(row, item) {
          let component = item.component;

          console.log(component)
          const modules = import.meta.glob('../../**/**/**/**/*.vue');
          let result = modules[component + '.vue'];
          console.log(result)
          if (result) {
            result().then(res => {
              this.bottomPanel = res.default
            }).catch(err => {
              console.log('err=', err)
            })
          }

          this.showIndex = 2
          // this.bottomPanel = item.component
          this.comTitle = item.info.title;
          console.log(this.bottomPanel)
          if (item.info.isInit) {
            this.$nextTick(() => {
              setTimeout(() => {
                this.$refs.comRef.init(row, item);
              }, 200)
            })
          }


        },
        // 弹框打开
        dialogFn(row, item) {

          let component = item.component;

          const modules = import.meta.glob('../../**/**/**/**/*.vue');
          // console.log(modules)
          let result = modules[component + '.vue'];
          // console.log(result)
          if (result) {
            result().then(res => {
              this.bottomPanel = res.default
            }).catch(err => {
              console.log('err=', err)
            })
          }
          this.dialogVisible = true;
          this.comTitle = item.info.title;
          this.dialogWidth = item.info.dialogWidth;
          if (item.info.isInit) {
            this.$nextTick(() => {
              setTimeout(() => {
                this.$refs.comRef.init(row, item);
              }, 200)
            })
          }
        },
        // 打开外部页面
        openUrl(row, item) {

          let url = item.info.url;
          if (!url.toString().startsWith("http")) {

            url = baseUrl + url;
          }
          if (item.info.prop && row) {
            url = url + '?' + item.info.prop + "=" + row[item.info.prop]
          }

          if (item.info.blank) {
            window.open(url);

          } else {
            window.location.href = url;
          }


        },
        // 修改弹框的状态
        updateDialogVisible(flg) {
          console.log(flg)
          this.dialogVisible = flg;
          this.getList();
        },
        comClose() {
          this.showIndex = 1;
          this.getList();
        }


      }


    },
    {}
)
</script>


<style scoped lang="scss">
:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 15px 20px;
}

.detail {
  height: 100%;
  overflow: auto;
  z-index: 999;

  .header {
    padding: 0 22px 20px 22px;
    font-size: 20px;
    color: rgba(0, 0, 0, .85);

    .header_div {
      display: inline-block;
      cursor: pointer;

      i {
        font-size: 24px;
        margin-right: 5px;
        vertical-align: top;
        margin-top: 3px;
      }

      &:hover {
        color: #1890ff;
      }

      span {
        font-weight: bold;
      }
    }
  }
}

.btm {
  margin: 0 8px;
  height: 1px;
  border-bottom: 1px solid #eee;
}

.el-tag {
  margin-right: 15px;
}

:deep(.avue-crud__img) {
  display: block;
}

</style>
